import axios from 'axios'
import store from '@/store'
import {
  ElMessage
} from 'element-plus';
import queryParams from './queryParams.js';

let loading;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.withCredentials = true

// 配置默认属性
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  // 超时时间
  timeout: 30000
});

// 添加拦截器
request.interceptors.request.use(config => {
  return config;
}, error => {
  return Promise.reject(error);
});

// 拦截响应
request.interceptors.response.use(response => {
  const res = response.data;
  if (res instanceof Blob) {
    return res;
  }
  if (res.code != 200) {
    ElMessage.error(res.msg || 'Error');
    if (res.code == 901) {
      store.commit('setUser', null);
      location.href = '/';
    }
    return Promise.reject(res.msg || 'Error')
  } else {
    return res
  }
}, error => {
  ElMessage.error('系统异常');
  return Promise.reject(error);
});


export default {
  post(url, params, type = 'form', config = {}) {
    if (type == 'form') {
      config.transformRequest = [function (data, headers) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded';
        return queryParams(data, false);
      }];
      if (params) {
        params.variableParameter = Date.now();
      }
      return request.post(url, params, config);
    } else {
      config.headers = {
        'Content-Type': 'application/json;charset=utf-8'
      }
      return request.post(url, params, config);
    }
  },
  get(url, params, config = {}) {
    return request.get(url, {
      params,
      ...config
    });
  },
  // put(url, params, config) {
  //   return request.put(url, params, config);
  // },
  // delete(url, params, config) {
  //   return request.delete(url, {
  //     params,
  //     ...config
  //   })
  // },
  download(url, params, filename, config) {
    if (typeof params === 'string') {
      filename = params
    }
    return request.post(url, params, {
      ...config,
      responseType: 'blob'
    }).then((r) => {
      const content = r;
      const blob = new Blob([content])
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = filename
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, filename)
      }
    }).catch((r) => {
      console.error(r)
      message.error('下载失败');
    })
  },
  upload(url, params, config) {
    let formData = new FormData();
    for (let prop in params) {
      formData.append(prop, params[prop]);
    }
    return request.post(url, formData, {
      ...config,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}
